package com.jintoufs.web.action.file;


import com.alibaba.fastjson.JSONObject;
import com.jintoufs.util.CosUtil;
import com.qcloud.cos.request.UploadFileRequest;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.annotation.Resource;

@Controller
@RequestMapping("/file")
public class FileAction {

    @Resource
    private CosUtil cosUtil;

    @RequestMapping("/uploadFile")
    @ResponseBody
    public AjaxMsg uploadFile(@RequestParam("file[]") CommonsMultipartFile[] files) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        StringBuilder attachment = new StringBuilder();
        if (files != null) {
            try {
                for (CommonsMultipartFile file : files) {
                    synchronized (this) {
                        String originFileName = file.getOriginalFilename();
                        String fileExtension = originFileName.substring(originFileName.lastIndexOf("."));
                        if(".jpg.png.jpeg.gif".contains(fileExtension)) {
                            UploadFileRequest uploadFileRequest = new UploadFileRequest("default", "/messageImage/" + System.currentTimeMillis() + originFileName, file.getBytes());
                            String result = cosUtil.uploadToCos(uploadFileRequest);
                            JSONObject object = JSONObject.parseObject(result);
                            if ("0".equals(object.get("code").toString())) {
                                String path = JSONObject.parseObject(object.get("data").toString()).get("access_url").toString();
                                path = path.replace("http://", "https://");
                                attachment.append(path);
                            }
                        }
                    }
                }
                ajaxMsg.setDatas(attachment.toString());
            } catch (Exception e) {
                e.printStackTrace();
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setMessage("上传发生错误!");
            }
        }
        return ajaxMsg;
    }
}
